import { delDeviceAlarmConfig, getDeviceAlarmConfigList } from "@/api/modules/iot/alarm";
import { getProfile } from "@/api/modules/model/profile";
import DialogBox from "@/components/DialogBox";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import AlarmLevel from "@/components/Sansan/Model/components/AlarmLevel";
import DataChart from "@/components/Sansan/Model/components/DataChart";
import BaseSearchForm from "@/components/SearchForm/BaseSearchForm";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { getDictList } from "@/utils/cacheUtil";
import { SchemaNodeKey, alarmParam } from "@/utils/constants";
import { dataFormat, duration } from "@/utils/format";
import { gotoPage } from "@/utils/routerUtil";
import { confirm, showMsg, showTips } from "@/utils/util";
import ConfigDetail from "@/views/iot/alarm/components/configDetail";
import { dayjs } from "element-plus";
import "./alarm.scss";
import HistAlarmList from "./components/histAlarmList";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const dicts = reactive({
			...alarmParam
		});
		const profile = ref();
		provide(SchemaNodeKey.profile, profile);
		const state = reactive({
			viewType: "device"
		});
		const initParam = reactive<any>({ prodOrDev: state.viewType });
		const searchParam = reactive<any>({
			collapsed: true
		});
		const proTable = ref<any>();
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "alarmType", label: proxy?.$t("alarmconfig.tablist_label.alarmType") },
			{ prop: "devSn", label: proxy?.$t("alarmconfig.tablist_label.devSn"), search: { el: "input" } },
			{ prop: "key", label: proxy?.$t("alarmconfig.tablist_label.key"), search: { el: "input" } },
			{ prop: "rule", label: proxy?.$t("alarmconfig.tablist_label.rule") },
			{ prop: "updateTime", label: proxy?.$t("alarmconfig.tablist_label.updateTime") },
			{ prop: "operation", label: proxy?.$t("alarmconfig.tablist_label.operation"), fixed: "right", width: 130 }
		];
		const warningLevel = ref<any>([]);
		const alarmType = ref<any>([]);
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
			warningLevel.value = await getDictList("warning_level");
			alarmType.value = await getDictList("alarm_type");
		});
		const dataCallback = (data: any) => {
			let res = Array.isArray(data)
				? { datalist: data }
				: {
						datalist: data.records,
						total: data.total || 0,
						pageIndex: data.current,
						pageSize: data.size
				  };
			res.datalist = res.datalist.map((item: any) => {
				item.id = `${item.devProductId}-${item.devName || item.devSn}-${item.key}`;
				return item;
			});
			return res;
		};
		const getTableList = async (params: any) => {
			return getDeviceAlarmConfigList({ ...params, ...searchParam });
			// return { result: { records: [{}] } };
		};
		const handerBtn = async (fn: string, row: any) => {
			let selected = row.selectList || [row];
			switch (fn) {
				case "history":
					if (selected.length != 1) {
						showMsg(proxy?.$t("alarmconfig.msg.history"), MessageType.warning);
						return;
					}
					const { result } = await getProfile({ idSn: selected[0].devSn });
					profile.value = result;
					dataChartDialog.detail = { ...selected[0] };
					dataChartDialog.title = `${proxy?.$t("alarmconfig.dialog_title.datachart")}-${
						selected[0].devName || selected[0].devSn
					}`;
					dataChartDialog.visible = true;
					break;
				case "conf":
					if (selected.length != 1) {
						showMsg(proxy?.$t("alarmconfig.msg.conf"), MessageType.warning);
						return;
					}
					configAlarmDialog.detail = { ...selected[0] };
					configAlarmDialog.title = `${proxy?.$t("alarmconfig.dialog_title.config")}-${selected[0].devName || selected[0].devSn}`;
					configAlarmDialog.visible = true;
					break;
				case "detail":
					if (selected.length != 1) {
						showMsg(proxy?.$t("alarmconfig.msg.detail"), MessageType.warning);
						return;
					}
					alarmHistoryDialog.detail = { ...selected[0] };
					alarmHistoryDialog.title = `${proxy?.$t("alarmconfig.dialog_title.history")}-${
						selected[0].devName || selected[0].devSn
					}`;
					alarmHistoryDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("alarmconfig.msg.del"), MessageType.warning);
						return;
					}
					delConfig(selected);
					break;
			}
		};
		const delConfig = (dataList: any) => {
			confirm({ content: proxy?.$t("alarmconfig.confirm.del") }).then(async flag => {
				if (!flag) return;
				let { code, message } = await delDeviceAlarmConfig({ sn: dataList[0].devSn, key: dataList[0].key });
				let ok = showTips(code, proxy?.$t("alarmconfig.tips.del"), message);
				ok && proTable.value.getTableList();
			});
		};

		//告警配置
		const configAlarmDialog = reactive({
			visible: false,
			detail: { key: "", devSn: "" },
			title: proxy?.$t("alarmconfig.dialog_title.config")
		});
		//历史数据
		const dataChartDialog = reactive<any>({
			title: proxy?.$t("alarmconfig.dialog_title.datachart"),
			detail: { key: "", devSn: "" },
			visible: false
		});
		//历史告警
		const alarmHistoryDialog = reactive<any>({
			title: proxy?.$t("alarmconfig.dialog_title.history"),
			detail: { key: "", devSn: "" },
			visible: false
		});

		const emptyTips = [
			proxy?.$t("alarmconfig.empty.tip1"),
			proxy?.$t("alarmconfig.empty.tip2"),
			proxy?.$t("alarmconfig.empty.tip3"),
			proxy?.$t("alarmconfig.empty.tip4"),
			proxy?.$t("alarmconfig.empty.tip5")
		].join("");
		return () => {
			return (
				<div class="alarm-config-page">
					<div class="monitor-head">
						<el-tabs
							v-model={state.viewType}
							onClick={() => {
								initParam.prodOrDev = state.viewType;
								proTable.value.getTableList();
							}}
						>
							<el-tab-pane label={proxy?.$t("alarmconfig.tab_pane.device")} name="device"></el-tab-pane>
							<el-tab-pane label={proxy?.$t("alarmconfig.tab_pane.product")} name="product"></el-tab-pane>
						</el-tabs>
					</div>
					{/*变量数据趋势*/}
					<DialogBox
						class="dialog-dense"
						hideFooter
						v-model:visible={dataChartDialog.visible}
						width="75vw"
						title={dataChartDialog.title}
					>
						{dataChartDialog.visible ? (
							<DataChart
								sn={dataChartDialog.detail.devSn}
								dataKey={dataChartDialog.detail.key}
								class="bg-gray-100"
								height="55vh"
							/>
						) : null}
					</DialogBox>
					{/*告警设置*/}
					<DialogBox
						title={configAlarmDialog.title}
						v-model:visible={configAlarmDialog.visible}
						footerLabel={[proxy?.$t("alarmconfig.dialog.footerLabel")]}
						width="65vw"
					>
						{configAlarmDialog.visible ? (
							<ConfigDetail
								sn={configAlarmDialog.detail.devSn}
								sensorKey={configAlarmDialog.detail.key}
								onChange={() => proTable.value.getTableList()}
							/>
						) : null}
					</DialogBox>
					{/*历史告警*/}
					<DialogBox
						title={alarmHistoryDialog.title}
						v-model:visible={alarmHistoryDialog.visible}
						footerLabel={[proxy?.$t("alarmconfig.dialog.footerLabel")]}
						width="65vw"
					>
						{alarmHistoryDialog.visible ? (
							<HistAlarmList fiexdTarget sn={alarmHistoryDialog.detail.devSn} sensorKey={alarmHistoryDialog.detail.key} />
						) : null}
					</DialogBox>
					<BaseSearchForm v-model:collapsed={searchParam.collapsed}>
						<el-form
							class="flex pt-4 pl-4 pr-4 bg-white"
							onKeyup={(e: KeyboardEvent) => e.keyCode == 13 && proTable.value.getTableList()}
						>
							<el-form-item class="search-item" label={proxy?.$t("alarmconfig.search_label.alarm_type")}>
								<el-select v-model={searchParam.alarmType} class="flex-1">
									{alarmType.value.map((item: any) => {
										return <el-option value={item.key} label={item.label}></el-option>;
									})}
								</el-select>
								{/* <el-input v-model={searchParam.alarmType} placeholder="告警类型" /> */}
							</el-form-item>
							<el-form-item class="search-item" label={proxy?.$t("alarmconfig.search_label.limit_type")}>
								<el-select v-model={searchParam.limitType} style="width:150px" clearable>
									{Object.values(alarmParam.warningMode).map(level => {
										return <el-option label={level.label} value={level.value}></el-option>;
									})}
								</el-select>
							</el-form-item>
							<el-form-item class="search-item" label={proxy?.$t("alarmconfig.search_label.sn")}>
								<el-input v-model={searchParam.sn} placeholder={proxy?.$t("alarmconfig.placeholder.sn")} style="width:150px" />
							</el-form-item>
							<el-form-item class="search-item" label={proxy?.$t("alarmconfig.search_label.keyName")}>
								<el-input
									v-model={searchParam.keyName}
									placeholder={proxy?.$t("alarmconfig.placeholder.keyName")}
									style="width:150px"
								/>
							</el-form-item>

							{/* 高级查询 */}
							{searchParam.collapsed ? null : (
								<el-form-item class="search-item" label={proxy?.$t("alarmconfig.search_label.alarm_level")}>
									<el-select v-model={searchParam.alarmLevel} clearable>
										{warningLevel.value.map((level: any) => {
											return <el-option label={level.label} value={level.key}></el-option>;
										})}
									</el-select>
								</el-form-item>
							)}
							<el-form-item class="search-item">
								<el-button type="primary" class="iconfont iconsearch" onClick={() => proTable.value.getTableList()}>
									{proxy?.$t("common.btn.search")}
								</el-button>
								<el-button
									class="iconfont iconsearch"
									onClick={() => {
										for (let key in searchParam) {
											searchParam[key] = null;
										}
										proTable.value.getTableList();
									}}
								>
									{proxy?.$t("common.btn.reset")}
								</el-button>
							</el-form-item>
						</el-form>
					</BaseSearchForm>
					<div class="mt-4 ignore-search-split">
						<ProTable
							ref={proTable}
							toolbar={["grid"]}
							viewType="grid"
							custSearch
							title={buttonsList.value.length ? "" : proxy?.$t("alarmconfig.tab_title.alarm_config")}
							onSearchCollapsed={val => (searchParam.collapsed = val)}
							columns={columns}
							initParam={initParam}
							gridSpan={6}
							requestApi={getTableList}
							dataCallback={dataCallback}
						>
							{{
								tableHeader: (scope: any) => {
									return buttonsList.value?.map((item: any) => {
										return (
											<el-button
												class={`iconfont ${item.icon}`}
												onClick={() => handerBtn(item.path, scope)}
												type={item.btnClass}
												disabled={state.viewType == "product" && item.path == "detail"}
											>
												{item.menuName}
											</el-button>
										);
									});
								},
								cardBody: (scope: any) => {
									return (
										<div class="config-card shadow-md">
											<div class="bg"></div>
											<div class="container">
												<div class="title flex content-center justify-between">
													<div class="flex-col flex-shrink truncate">
														<el-tooltip show-after={500} content={`加载设备详情（${scope.row.devName || scope.row.devSn}）`}>
															<div
																class="cursor-pointer primary-color overflow master-title"
																onClick={() => {
																	state.viewType == "product"
																		? gotoPage(RouterPath.productDetail, {
																				id: scope.row.devProductId
																		  })
																		: gotoPage(RouterPath.deviceDetail, { sn: scope.row.devSn });
																}}
															>
																{scope.row.devName || scope.row.devSn}
															</div>
														</el-tooltip>
														<div class="sub-title" title="查看历史数据">
															<el-link
																type="primary"
																onClick={() => handerBtn("history", scope.row)}
																disabled={state.viewType == "product"}
															>
																{scope.row.key}
															</el-link>
														</div>
													</div>
													{buttonsList.value.find((item: any) => item.path == "del" || item.path == "mod") ? (
														<el-dropdown
															v-slots={{
																dropdown: () => {
																	return (
																		<el-dropdown-menu>
																			{buttonsList.value.find((item: any) => item.path == "conf") ? (
																				<el-dropdown-item onClick={() => handerBtn("conf", scope.row)}>
																					{buttonsList.value.find((item: any) => item.path == "conf").menuName}
																				</el-dropdown-item>
																			) : null}
																			{buttonsList.value.find((item: any) => item.path == "del") ? (
																				<el-dropdown-item onClick={() => handerBtn("del", scope.row)}>
																					{buttonsList.value.find((item: any) => item.path == "del").menuName}
																				</el-dropdown-item>
																			) : null}
																		</el-dropdown-menu>
																	);
																}
															}}
														>
															<el-link underline={false}>
																<i class="iconfont iconmore-vertical" style="font-size:22px" />
															</el-link>
														</el-dropdown>
													) : null}
												</div>
												<el-scrollbar class="body">
													<div class="panel">
														{scope.row.warning?.map((conf: any) => {
															let item = Object.values(alarmParam.warningMode).find(item => item.value == conf.warningMode);
															return (
																<div class="alarm-group w-full">
																	<div class="type-label">{conf.alarmType}</div>
																	<div class="param-info">
																		<div class="param-label">{item?.label} </div>
																		<div class="param-value">
																			{/* 上限 */}
																			{conf.warningMode == alarmParam.warningMode.max.value ? (
																				<div>{conf.warningUlimit || 0}</div>
																			) : null}

																			{/* 下限 */}
																			{conf.warningMode == alarmParam.warningMode.min.value ? (
																				<div>{conf.warningDlimit || 0}</div>
																			) : null}

																			{/* 上下限 */}
																			{conf.warningMode == alarmParam.warningMode.range.value ? (
																				<div>
																					{conf.warningDlimit || 0} ~ {conf.warningUlimit || 0}
																				</div>
																			) : null}

																			{/* 下限 */}
																			{conf.warningMode == alarmParam.warningMode.eq.value ? (
																				<div>{conf.warningElimit || 0}</div>
																			) : null}
																		</div>
																	</div>
																</div>
															);
														})}
													</div>
												</el-scrollbar>
												<div class="footer flex justify-between pr-2">
													{/* <el-button
														class="iconfont icontrash-2"
														link
														title="删除告警配置"
														type="danger"
														disabled={!buttonsList.value.find((item: any) => item.path == "del")}
														onClick={() => handerBtn("del", scope.row)}
													>
														删除配置
													</el-button> */}
													{state.viewType == "product" ? (
														<div class="flex-1"></div>
													) : (
														<el-button
															class="iconfont iconbx-list-ol"
															link
															title={proxy?.$t("alarmconfig.btn_title.hist")}
															type="primary"
															disabled={
																state.viewType == "product" || !buttonsList.value.find((item: any) => item.path == "detail")
															}
															onClick={() => handerBtn("detail", scope.row)}
														>
															{proxy?.$t("alarmconfig.btn.hist")}
														</el-button>
													)}
													<el-button
														class="iconfont iconsettings"
														link
														title={proxy?.$t("alarmconfig.btn_title.config")}
														type="primary"
														disabled={!buttonsList.value.find((item: any) => item.path == "conf")}
														onClick={() => handerBtn("conf", scope.row)}
													>
														{proxy?.$t("alarmconfig.btn.alarm_config")}
													</el-button>
												</div>
											</div>
										</div>
									);
								},

								alarmType: (scope: any) => {
									return (
										<span>
											{!scope.row.warning || !scope.row.warning.length ? "--" : null}
											{scope.row.warning
												?.map((item: any) => {
													return item.alarmType;
												})
												.join(",")}
										</span>
									);
								},
								duration: (scope: any) => {
									return duration(dayjs(scope.row.createTime));
								},
								rule: (scope: any) => {
									return (
										<el-popover show-after={500}>
											{{
												reference() {
													return (
														<el-link
															type="primary"
															disabled={!buttonsList.value.find((item: any) => item.path == "conf")}
															onClick={() => handerBtn("conf", scope.row)}
														>
															{!scope.row.warning || !scope.row.warning.length ? "--" : null}
															{scope.row.warning
																?.map((conf: any) => {
																	return Object.values(alarmParam.warningMode).find(item => item.value == conf.warningMode)
																		?.label;
																})
																.join(",")}
														</el-link>
													);
												},
												default() {
													return (
														<div class="leading-6">
															{!scope.row.warning || !scope.row.warning.length ? "无告警配置" : null}
															{scope.row.warning?.map((conf: any) => {
																let item = Object.values(alarmParam.warningMode).find(item => item.value == conf.warningMode);
																return (
																	<>
																		<div class="flex pb-4">
																			<div class="w-20 text-right">{item?.label}：</div>
																			{/* 上限 */}
																			{conf.warningMode == alarmParam.warningMode.max.value ? (
																				<div>{conf.warningUlimit}</div>
																			) : null}

																			{/* 下限 */}
																			{conf.warningMode == alarmParam.warningMode.min.value ? (
																				<div>{conf.warningDlimit}</div>
																			) : null}

																			{/* 上下限 */}
																			{conf.warningMode == alarmParam.warningMode.range.value ? (
																				<div>
																					{conf.warningDlimit} ~ {conf.warningUlimit}{" "}
																				</div>
																			) : null}

																			{/* 下限 */}
																			{conf.warningMode == alarmParam.warningMode.eq.value ? (
																				<div>{conf.warningElimit}</div>
																			) : null}
																		</div>
																	</>
																);
															})}
														</div>
													);
												}
											}}
										</el-popover>
									);
								},
								key: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => handerBtn("history", scope.row)}>
											{scope.row.key}
										</el-link>
									);
								},
								devSn: (scope: any) => {
									return (
										<el-link type="primary" onClick={() => gotoPage(RouterPath.deviceDetail, { sn: scope.row.devSn })}>
											<div class="master-title">{scope.row.devName || scope.row.devSn}</div>
										</el-link>
									);
								},
								warningMode: (scope: any) => {
									return Object.values(dicts.warningMode).find(item => item.value == scope.row.warningMode)?.label;
								},
								level: (scope: any) => {
									return <AlarmLevel v-model={scope.row.level} />;
								},
								isError: (scope: any) => {
									return Object.values(dicts.isError).find(item => item.value == scope.row.isError)?.label;
								},
								autoDone: (scope: any) => {
									return Object.values(dicts.autoDone).find(item => item.value == scope.row.autoDone)?.label;
								},
								triggerType: (scope: any) => {
									return Object.values(dicts.triggerType).find(item => item.value == scope.row.triggerType)?.label;
								},
								warningType: (scope: any) => {
									return Object.values(dicts.warningType).find(item => item.value == scope.row.warningType)?.label;
								},
								updateTime: (scope: any) => {
									return dataFormat("datetime", scope.row.updateTime);
								},
								operation: (scope: any) => {
									return (
										<>
											<el-link
												type="danger"
												disabled={!buttonsList.value.find((item: any) => item.path == "del")}
												onClick={() => handerBtn("del", scope.row)}
											>
												{proxy?.$t("alarmconfig.operation.del")}
											</el-link>
											<el-link
												type="primary"
												disabled={!buttonsList.value.find((item: any) => item.path == "detail")}
												onClick={() => handerBtn("detail", scope.row)}
											>
												{proxy?.$t("alarmconfig.operation.more")}
											</el-link>
										</>
									);
								},
								empty: () => {
									return (
										<Empty
											class="text-left leading-6"
											showButton={false}
											title={proxy?.$t("alarmconfig.empty.title")}
											subtitle={emptyTips}
										/>
									);
								}
							}}
						</ProTable>
					</div>
				</div>
			);
		};
	}
});
